<?php
/**
 * 
 * 连续登陆奖励
 * @author will
 *
 */
class Awards_Login {
	/**
	 * 获取奖励金额
	 * @param <int> $times
	 */
	static public function getAwardsMoney($times = 0) {
		$awards = array(
			1 => 0,
			2 => 5,
			3 => 12,
			4 => 18,
			5 => 25,
		);
		
		if($times <= 0) {
			return 0;
		} else if (isset($awards[$times])) {
			return $awards[$times];
		} else {
			return $awards[5];
		}
	}
	
	/**
	 * 获取登陆奖励信息
	 * @param <int> $uin
	 * @param <boolean> $add_data
	 */
	static public function getInfo($uin , $add_data = false) {
		$Db = loadDB();
		
		$db_result = $Db->getOne("SELECT * FROM `awards_login` WHERE `uin` = {$uin}");
		$result = $db_result;
		
		// 判断是否要加1天
		if($add_data) {
			$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
			if(empty($result)) {
				$insert_data = array(
					'uin' => $uin,
					'login_time' => $time_now,
					'times' => 1,
				);
				$Db->doInsert('awards_login' , $insert_data);
				
				$result = $insert_data;
			} else {
				$today_timestamp = strtotime( date('Y-m-d' , $time_now) );
				$yestoday_timestamp = $today_timestamp - 86400;
				if($result['login_time'] < $yestoday_timestamp) {
					// 上次登陆是2天以前的，没有连续登陆
					$update_data = array(
						'login_time' => $time_now,
						'times' => 1,
					);
					$Db->doUpdate('awards_login' , $update_data , "`uin` = {$uin}");
					
					$result = $update_data;
				} else if($result['login_time'] < $today_timestamp) {
					// 上次登陆是昨天，是连续登陆
					$update_data = array(
						'login_time' => $time_now,
						'times' => $result['times'] + 1,
					);
					$Db->doUpdate('awards_login' , $update_data , "`uin` = {$uin}");
					
					$result = $update_data;
				} else {
					// 上次登陆是今天，不用修改库
				}
			}
		}
		
		if(!isset($result['uin'])) {
			$result['uin'] = $uin;
		}
		
		if(!isset($result['times'])) {
			$result['times'] = 0;
		}
		
		return $result;
	}
	
	
	static public function addAwards($uin , &$awards_login) {
		$Db = loadDB();
		
		$awards_login = self::getInfo($uin , true);
		$awards_money = self::getAwardsMoney($awards_login['times']);
		
		$awards_login['awards_money'] = $awards_money;
		
		if($awards_money <= 0) {
			return 0;
		}
		
		// 给用户加钱
		loadLib('Money');
		$code = Money::update($uin , $awards_money);
		if($code != 0) {
			return $code;
		}
		
		// 加完后，更新 awrads_login 表
		$time_now = isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time();
		$update_data = array(
			'login_time' => $time_now,
			'times' => 0,
		);
		$Db->doUpdate('awards_login' , $update_data , "`uin` = {$uin}");
		
		return 0;
	} 
	
}


# end of script
